<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm } from '@sa/alova/client';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { createStorageFile, updateStorageFile } from '@/service/api/infra/storage';
import { $t } from '@/locales';

defineOptions({
  name: 'StorageFileDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Model | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增文件',
    edit: '编辑文件'
  };
  return titles[props.operateType];
});

const {
  loading: submitting,
  reset,
  form,
  updateForm
} = useForm(formData => (props.operateType === 'add' ? createStorageFile(formData) : updateStorageFile(formData)), {
  initialForm: {
    id: 0,
    path: null,
    configId: null,
    url: null,
    name: null,
    type: null,
    size: null
  } as Api.Model,
  resetAfterSubmitting: true
});

type RuleKey = Extract<keyof Api.Model, 'userName' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  userName: defaultRequiredRule,
  status: defaultRequiredRule
};

function handleInitModel() {
  if (props.operateType === 'edit' && props.rowData) {
    updateForm(props.rowData);
  } else if (props.operateType === 'add') {
    reset();
  }
}

function closeDrawer() {
  visible.value = false;
}

const uploadRef = ref<any>(); // Declare template ref

async function handleSubmit() {
  await validate();

  // Handle form submission
  // await submit();
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    restoreValidation();
    handleInitModel();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" width="400">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="form" :rules="rules">
        <NFormItem label="存储配置" path="configId">
          <PorSelect
            v-model:value="form.configId"
            url="/infra/storage/storageConfig/simpleList"
            value-to-number
            label-field="name"
            value-field="id"
          ></PorSelect>
        </NFormItem>
        <NFormItem label="上传文件" path="url">
          <PorUpload ref="uploadRef" v-model:value="form.url" action="/infra/storage/storageFile/uploadFile" :max="1">
            <NButton>选择文件</NButton>
          </PorUpload>
        </NFormItem>

        <NFormItem span="24 s:12 m:6" label="文件 URL" path="url" class="pr-24px">
          <NInput v-model:value="form.url" placeholder="文件 URL" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitting" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
